"use strict";

const _ = require("lodash");
const os = require("os");
const KError = require("./KError");
const seq = require("sequelize");
const Op = seq.Op;

function FmtWhere(body) {
  const {
    id,
    mobile,
    name,
    gender,
    store,
    remark,
    userId,
    deptId,
    keyword,
    deptIdList,
  } = body;
  let where = {};
  if (id) where.id = +id;
  if (mobile) where.mobile = { [Op.like]: `%${mobile}%` };
  if (name) where.name = { [Op.like]: `%${name}%` };
  if (gender) where.gender = +gender;
  if (store) where.store = { [Op.like]: `%${store}%` };
  if (remark) where.remark = { [Op.like]: `%${remark}%` };
  if (userId) where.userId = userId;
  if (deptId) where.deptId = { [Op.like]: `%${deptId}%` };
  if (keyword)
    where[Op.or] = [
      { name: { [Op.like]: `%${keyword}%` } },
      {
        mobile: { [Op.like]: `%${keyword}%` },
      },
    ];
  if (deptIdList && _.isArray(deptIdList))
    where.deptId = { [Op.in]: deptIdList };
  if (!keyword && Object.keys(where).length === 0) return {};
  return where;
}

/**
 * 格式化查询条件
 */
exports.FmtSearch = (body) => {
  if (_.isNil(body)) throw KError.InvalidFormatData("FmtSearch args is Nil");
  let where = FmtWhere(body);
  return { where, order: [["createdAt", "DESC"]] };
};

/**
 * 格式化查询条件 列表 分页
 */
exports.FmtSearchAll = (body) => {
  if (_.isNil(body)) throw KError.InvalidFormatData("FmtSearch args is Nil");
  let where = FmtWhere(body);
  const { keyword, page, size } = body;
  let condition = {
    order: [["createdAt", "DESC"]],
  };
  if (keyword || Object.keys(where).length > 0) condition.where = where;
  let limit = 10;
  let offset = 0;
  if (!_.isNil(size) && _.isNumber(+size)) limit = +size;
  if (!_.isNil(page) && _.isNumber(+page) && +page !== 0)
    offset = (page - 1) * limit;
  condition.offset = offset;
  condition.limit = limit;
  return condition;
};

/**
 * 获取请求服务机器的ip
 * @function getRemoteIP
 * @param {Object} req
 * @return {String}
 */
exports.getRemoteIP = (req) => {
  return (
    req.headers["x-forwarded-for"] ||
    (req.connection && req.connection.remoteAddress) ||
    (req.socket && req.socket.remoteAddress) ||
    (req.connection &&
      req.connection.socket &&
      req.connection.socket.remoteAddress) ||
    ""
  );
};

/**
 * 获取本地服务器ip
 * @function getLocalIP
 * @return {String} localIP
 */
exports.getLocalIP = () => {
  const interfaces = os.networkInterfaces();
  let localIP = "";
  Object.keys(interfaces).forEach(function (name) {
    interfaces[name].forEach(function (f) {
      if ("IPv4" !== f.family || f.internal !== false) {
        return;
      }
      localIP += f.address + ";";
    });
  });
  return localIP;
};
